const app = getApp();
const api = require("../../server/Api.js");
const payHelper = require("../../utils/pay.js")
const util = require("../../utils/util.js");
Page({
  data: {
    showCancelDialog: false,
    orderId: "",
    statusInfo: {
      0: {
        statusName: '订单已取消',
        statusDesc: '订单取消，交易关闭。',
        btns: []
      },
      2: {
        statusName: '订单待配送',
        statusDesc: '请尽快送达，不要超时咯！',
        showAddress: true,
        btns: [{
          name: '开始配送',
          color: 'red'
        }]
      },
      3: {
        statusName: '订单配送中',
        statusDesc: '请尽快送达，不要超时咯！',
        showAddress: true,
        btns: [{
          name: '确认送达',
          color: 'red'
        }]
      },
      4: {
        //已完成
        statusName: '订单已送达',
        statusDesc: '商品已成功送到客户地址。',
        showAddress: true,
        btns: [],
      },
      98: {
        //待自提
        statusName: '订单待提货',
        statusDesc: '到店提货，请提前准备好商品。',
        btns: [{
          name: '提醒提货',
          color: 'gray'
        }]
      },
      97: {
        //已自提
        statusName: '订单已提货',
        statusDesc: '客户已成功提走商品。',
        btns: []
      },
      96: {
        //已退款
        statusName: '订单已退款',
        statusDesc: '订单取消，交易关闭。',
        btns: []
      }
    },
    item: {},
    distance: "?km"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.orderId) {
      this.setData({
        orderId: options.orderId
      })
    }
    this.queryOrderDetail();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  //查询订单详情
  queryOrderDetail: function() {
    let that = this;
    let orderId = this.data.orderId;
    app.showLoading();
    api.queryOrderDetail(orderId, 0, 0).then(res => {
      tt.hideLoading()
      res = util.formatOrderStatus(res);
      if (res.orderStatus === 98 && res.payStatus === 1 && res.payTime && res.list && res.list.length > 0 && res.list[0].receiptInterval) {
        that.data.statusInfo[res.orderStatus].statusDesc = "商品预计" + app.getZtDate(res.deliveryTime) + "可提货，届时请短信通知客户"
        that.setData({
          statusInfo: that.data.statusInfo
        })
      }
      for (let i = 0; i < res.list.length; i++) {
        res.list[i].goodsImage = app.resetImageUrl(res.list[i].goodsImage, 172, 172)
      }
      that.setData({
        item: res
      })
      if (that.data.statusInfo[that.data.item.orderStatus].showAddress) {
        app.globalData.qqmapsdk.calculateDistance({
          mode: "straight",
          to: res.addressLatitude + "," + res.addressLongitude,
          success: function(res) {
            if (res.result.elements.length > 0) {
              that.setData({
                distance: app.setMtoKm(res.result.elements[0].distance)
              })
            }
          },
          fail: function(error) {
            console.error("获取距离失败", error);
          },
        });
      }

    }).catch(msg => {
      tt.hideLoading()
      let message = typeof msg == "string" ? msg : msg.message;
      app.showToast(message)
    })
  },

  opertionTap: function(e) {
    let operName = e.currentTarget.id; //操作类型
    switch (operName) {
      case "取消订单":
        this.setData({
          operType: 1
        })
        this.showCancelDialog();
        break;
      case "删除订单":
        this.setData({
          operType: 2
        })
        this.showCancelDialog();
        break;
      case "开始配送":
        this.updateOrderStatus(this.data.item.orderId, 1)
        break;
      case "确认送达":
        this.updateOrderStatus(this.data.item.orderId, 2)
        break;
      case "扫码核销":
        this.toscan();
        break;
      case "提醒提货":
        api.notifyBuyersByOrderId(this.data.item.orderId).then(() => {
          app.showToast("已成功提醒客户")
        }).catch(msg => {
          let message = typeof msg == "string" ? msg : msg.message;
          app.showToast("通知失败!" + message);
        })
        break;
    }
  },

  //请求删除or取消订单
  onConfirm: function() {
    let that = this;
    let curOrder = this.data.item;
    let operType = this.data.operType;
    if (operType == 2) {
      app.showLoading()
      api.deleteOrder(curOrder.orderId).then(res => {
        tt.hideLoading()
        tt.showToast({
          title: '删除成功',
        })
        setTimeout(function() {
          tt.navigateBack({
            delta: 1,
          })
        }, 1000)
      }).catch(msg => {
        tt.hideLoading()
        let message = typeof msg == "string" ? msg : msg.message;
        app.showToast(message);
      })
    } else { //取消订单
      api.cancelOrder(curOrder.orderId).then(res => {
        that.queryOrderDetail();
        tt.showToast({
          title: '取消成功',
        })
      }).catch(msg => {
        let message = typeof msg == "string" ? msg : msg.message;
        app.showToast(message);
      })
    }
  },

  //显示是否弹出取消订单的操作
  showCancelDialog: function() {
    this.setData({
      showCancelDialog: true,
    })
  },
  //隐藏所有弹窗
  hiddenDialog: function(e) {
    this.setData({
      showCancelDialog: false
    })
  },
  copyTxt: function(e) {
    app.copyTxt(e);
    return;
  },
  viewmap(e) {
    console.log(e);
    tt.openLocation({
      latitude: parseFloat(e.currentTarget.dataset.lat),
      longitude: parseFloat(e.currentTarget.dataset.lng),
      scale: 18
    })
  },
  updateOrderStatus(orderId, status) {
    api.UpdateOrderStatus(orderId, status).then(() => {
      this.queryOrderDetail();
    }).catch(msg => {
      let message = typeof msg == "string" ? msg : msg.message;
      app.showToast(message);
    })
  },
  toscan: function() {
    let that = this;
    // 只允许从相机扫码
    tt.scanCode({
      //onlyFromCamera: true,
      success(res) {
        console.log(res)
        api.verificationOrder(res.result, app.globalData.userShopId[0].id).then(() => {
          //app.showToast("订单已核销")
          tt.showModal({
            title: '订单已核销',
            showCancel: false
          })
          that.queryOrderDetail()
        }).catch(msg => {
          let message = typeof msg == "string" ? msg : msg.message;
          app.showToast("核销失败!" + message);
        })
      }
    })
  },
  tel() {
    if (this.data.item.telephone) {
      app.makePhoneCall(this.data.item.telephone)
    } else {
      app.showToast("未配置号码")
    }
  }
})